/**
 * Created by Jimmy on 2018/12/11.
 */
<template>
  <div class="people-managment ">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/panel/project/cost' }">项目成本</el-breadcrumb-item>
    </el-breadcrumb>
    <el-button type="primary" size="small" class="fr mb-10" @click="editRecord">新建</el-button>

    <div class="serh">
      <el-input placeholder="请输入项目名称搜索" v-model="searchProjectInput" class="input-with-select">
        <el-button slot="append" icon="el-icon-search" @click="searchProjectCost"></el-button>
      </el-input>
    </div>
    <div class="tble">
      <el-table
        :data="tableData"
        border
        :stripe= 'true'
        style="width:100%">
        <el-table-column type="index" label="序号" align="center" width="50"></el-table-column>
        <el-table-column prop="CostDate" label="日期" align="center" width="100"></el-table-column>
        <el-table-column prop="TypeName" label="费用类型" align="center" width="100"></el-table-column>
        <el-table-column prop="CostAmount" label="金额" align="center" width="100"></el-table-column>
        <el-table-column label="关联项目" align="center" class="link-txt">
          <template slot-scope="scope">
            <el-button type="text" @click="detailCheck(scope.row.ProjectID)">{{scope.row.ProjectName}}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="Desc" label="备注" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" plain @click="deleteRecord(scope.row)">删除</el-button>
            <el-button type="primary" size="mini" @click="editRecord(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="count">
      <div class="c-d c-d-1">合计</div>
      <div class="c-d ">{{tableData.length}}</div>
      <div class="c-d c-d-d">项，共</div>
      <div class="c-d ">{{totalAmount.toFixed(2)}}</div>
      <div class="c-d c-d-y">元</div>
      <el-button type="success" :loading="loading" size="small" icon="el-icon-download" @click="downloadCost">导出</el-button>
    </div>
    <!--<el-pagination-->
      <!--@current-change="handleCurrentChange"-->
      <!--:current-page="currentPage"-->
      <!--:pageSize="pageSize"-->
      <!--layout="total, prev, pager, next, jumper"-->
      <!--:total="total">-->
    <!--</el-pagination>-->
    <el-dialog center title="项目成本" :visible.sync="dialogFormVisible" class="edit-p-dialog">
      <el-form v-model="form" ref="form" label-width="120px">
        <el-form-item label="日期：">
          <el-date-picker
            v-model="form.CostDate"
            type="date"
            placeholder="请选择费用日期"
            value-format="yyyy-MM-dd"
            size="small">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="费用类型：">
          <el-select v-model="form.TypeID" filterable placeholder="请选择" size="small">
            <el-option
              v-for="item in TypeIDOptions"
              :key="item.index"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="金额：">
          <el-input v-model="form.CostAmount" size="small" placeholder="请输入费用金额"></el-input>
        </el-form-item>
        <el-form-item label="关联项目：">
          <div v-if="hasassociatedProject">
            <el-input v-model="associatedProject.ProjectName" size="small" disabled>
              <el-button slot="append" icon="el-icon-circle-close-outline" @click="deleteAssociatedProject"></el-button>
            </el-input>
          </div>
          <div v-else>
            <el-popover
              placement="bottom"
              width="600"
              trigger="click">
              <el-input placeholder="请输入项目名称搜索" v-model="searchInput" class="input-with-select">
                <el-button slot="append" icon="el-icon-search" @click="searchProject"></el-button>
              </el-input>
              <div class="show-search">
                <el-table
                  :data="searchData"
                  highlight-current-row
                  @current-change="clickTable">
                  <el-table-column width="150" property="ProjectNumber" label="项目编号"></el-table-column>
                  <el-table-column width="450" property="ProjectName" label="项目名称"></el-table-column>
                </el-table>
              </div>
              <el-button slot="reference" type="primary" icon="el-icon-plus" size="mini" >输入项目名称搜索</el-button>
            </el-popover>
          </div>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 4}"
            placeholder="请输入内容"
            v-model="form.Desc">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmEditRecord">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data(){
      return {
        loading:false,
        searchProjectInput:'',
        TypeIDOptions:[
          {value:1,label:'材料'},
          {value:2,label:'交通'},
          {value:3,label:'住宿'},
          {value:4,label:'分包劳务'},
          {value:5,label:'办公'},
          {value:6,label:'其他'},
        ],
        totalAmount:0,
        searchData:[],
        searchInput:'',
        token:'',
        tableData:[],
        dialogFormVisible:false,
        currentPage:1,
        pageSize:10,
        total:0,
        rowid:'',
        hasassociatedProject:false,
        associatedProject:{},
        form:{
          CostDate:'',
          CostAmount:'',
          Desc:'',
          TypeID:'',
        }
      };
    },
    created: function(){
      let user = JSON.parse(window.localStorage.getItem('access-user'))
      this.token = user.Token
      this.loadList(this.currentPage,true)
    },
    methods: {
      downloadCost(){
        this.loading = true
        this.$http.post(this.domain + '/cost/report',
          {
            token:this.token,
            name:this.searchProjectInput
          }
        ).then((response) => {
          if (response.data.Success) {
            let downloadElement = document.createElement('a');
            let href = this.domain +response.data.URL; //创建下载的链接
            downloadElement.href = href;
            downloadElement.download = response.data.Title; //下载后文件名
            document.body.appendChild(downloadElement);
            downloadElement.click(); //点击下载
            document.body.removeChild(downloadElement); //下载完成移除元素
            window.URL.revokeObjectURL(href);
          } else {
            this.$message.error(response.data.Msg)
          }
          this.loading = false
        }).catch(function (response) {
          this.$message.error(response.data)
          this.loading = false
        })
      },
      searchProjectCost(){
        if (this.searchProjectInput === '') {
          this.loadList(this.currentPage,true)
        } else {
          this.$http.post(this.domain + '/cost/search',
            {
              token:this.token,
              name:this.searchProjectInput
            }
          ).then((response) => {
            if (response.data.Success) {
              this.tableData = response.data.Data
              this.totalAmount = 0
              this.tableData.forEach((obj) => {
                this.totalAmount += obj.CostAmount
              })
              this.$message.success(response.data.Msg)
            } else {
              this.$message.error(response.data.Msg)
            }
          }).catch(function (response) {
            this.$message.error(response.data)
          })
        }
      },
      clickTable(val) {
        this.hasassociatedProject = true
        this.associatedProject.ProjectName = val.ProjectName
        this.associatedProject.ProjectID = val.ID
      },
      searchProject () {
        this.$http.post(this.domain + '/project/search',
          {
            token:this.token,
            name:this.searchInput
          }
        ).then((response) => {
          if (response.data.Success) {
            this.searchData = response.data.Data
          } else {
            this.$message.error(response.data.Msg)
          }
        }).catch(function (response) {
          this.$message.error(response.data)
        })
      },
      confirmEditRecord(){
//        console.log(this.form)
        var args = {
          token: this.token,
          costamounnt:this.form.CostAmount === undefined || this.form.CostAmount === "" ? 0:parseFloat(this.form.CostAmount),
          desc:this.form.Desc === undefined ? "":this.form.Desc
        }
        if (this.form.CostDate !== undefined) {
          args.costdate = this.form.CostDate
          if (this.form.CostDate.length === 10) {
            args.costdate += " 00:00:00"
          }
        } else {
          this.$message.error("请选择费用日期")
          return
        }
        if(this.form.TypeID !== undefined && this.form.TypeID !== ""){
          args.typeid = parseInt(this.form.TypeID)
        } else {
          this.$message.error("请选择费用类型")
          return
        }
        if(this.hasassociatedProject){
          args.projectid = this.associatedProject.ProjectID
        } else {
          args.projectid = 0
        }
        if (this.rowid) {
          args.id = this.rowid
        }
//        console.log(args)
        this.$http.post(this.domain + '/cost/edit',
          args
        ).then((response) => {
          if (response.data.Success) {
            this.$message.success(response.data.Msg)
            this.loadList(this.currentPage,false)
          } else {
            this.$message.error(response.data.Msg)
          }
        }).catch(function (response) {
          this.$message.error(response.data)
        })
        this.dialogFormVisible = false
      },
      deleteRecord(row) {
        if (row.ID) {
          this.$confirm('确认删除吗?', '提示', {
            confirmButtonClass: 'el-button--warning'
          }).then(() => {
            this.$http.post(this.domain + '/cost/delete',
              {
                token:this.token,
                id:parseInt(row.ID)
              }
            ).then((response) => {
              if (response.data.Success) {
                this.$message.success(response.data.Msg)
                this.loadList(this.currentPage,false)
              } else {
                this.$message.error(response.data.Msg)
              }
            }).catch((response) => {
              this.$message.error(response.data)
            })
          }).catch(() => {})
        }
      },
      editRecord (row) {
        if(row.ID) {
          this.rowid = row.ID
          if (row.ProjectID !== 0) {
            this.hasassociatedProject = true
            this.associatedProject.ProjectName = row.ProjectName
            this.associatedProject.ProjectID = row.ProjectID
          } else {
            this.hasassociatedProject = false
            this.associatedProject = {}
          }
          this.form = {
            TypeID:row.TypeID,
            CostDate:row.CostDate,
            CostAmount:row.CostAmount,
            Desc:row.Desc,
          }
        } else {
          this.rowid = ''
          this.form = {
            CostDate:'',
            CostAmount:'',
            Desc:'',
            TypeID:'',
          }
          this.hasassociatedProject = false
          this.associatedProject = {}
        }
        this.dialogFormVisible = true
//        console.log(this.form)
//        console.log(this.hasassociatedProject)
//        console.log(this.associatedProject)
      },
      loadList(page,flag){
        this.$http.post(this.domain + '/cost/list',
          {
            token:this.token,
            page:page
          }
        ).then((response) => {
          if (response.data.Success) {
//            console.log(response.data)
            this.tableData = response.data.Data
//            this.total = response.data.Total
            this.totalAmount = 0
            this.tableData.forEach((obj) => {
              this.totalAmount += obj.CostAmount
            })
            if (flag) {
              this.$message.success(response.data.Msg)
            }
          } else {
            this.$message.error(response.data.Msg)
          }
        }).catch(function (response) {
          this.$message.error(response.data)
        })
      },
      handleCurrentChange(page){
        this.currentPage = page
        this.loadList(this.currentPage,true)
      },
      deleteAssociatedProject() {
        this.hasassociatedProject = false
        this.associatedProject = {}
      },
      detailCheck(ID){
        if (ID !== 0) {
          let routeData = this.$router.resolve({
            path: '/panel/project/detail',
            query: {
              id: ID
            }
          })
          window.open(routeData.href, '_blank')
        }
      },
    }
  }
</script>
<style>
  .people-managment>h4{
    line-height: 36px;
    height: 36px;
  }
  .edit-p-dialog .el-dialog__body{
    padding-right: 60px;
  }
  .edit-p-dialog  .el-dialog{
    width: 450px;
  }
  .locked{
    color: red;
    font-size: 12px;
  }
  .el-form-item__label{
    font-weight: 700;
  }
  .show-search{
    height: 250px;
    overflow: scroll;
  }
</style>
